package org.itzheng.yuezhi.real.main;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import org.itzheng.yuezhi.BaiDuLbsUtil;
import org.itzheng.yuezhi.R;
import org.itzheng.yuezhi.activity.NewsListActivity;
import org.itzheng.yuezhi.adapter.BaseRecyclerViewAdapter;
import org.itzheng.yuezhi.base.BaseFragment;
import org.itzheng.yuezhi.constant.Extras;
import org.itzheng.yuezhi.constant.HttpUrl;
import org.itzheng.yuezhi.entity.NewsChannelEntity;
import org.itzheng.yuezhi.entity.WeatherQueryEntity;
import org.itzheng.yuezhi.utils.JsonUtils;
import org.itzheng.yuezhi.utils.MyLog;
import org.itzheng.yuezhi.utils.MyOkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Title:<br>
 * Description: <br>
 * Company: <br>
 *
 * @author ZhengYongdong
 * @email ItZheng@ZoHo.com
 * @date 2016/6/25 0025
 */
public class HomeFragment extends BaseFragment {
    View rootView;
    @BindView(R.id.tv_home_weather_info)
    TextView tv_home_weather_info;
    /**
     * 新闻列表集合
     */
    List<NewsChannelEntity.ShowapiResBody.ChannelList> channelLists = new ArrayList<>();
    /**
     * 新闻列表
     */
    RecyclerView rcv_home_news_channel;
    Activity mActivity;
    List<WeatherQueryEntity.Result> weatherQueryEntityResult;

    @Override
    protected View onCreateView(LayoutInflater inflater, ViewGroup container) {
        mActivity = getActivity();
        if (rootView == null) {
            rootView = View.inflate(getActivity(), R.layout.fragment_home, null);
            ButterKnife.bind(this, rootView);
            initData();
        }

        return rootView;
    }

    private void initData() {
        getLoacation();
        getNewsChannel();
    }

    /**
     * 获取新闻分类列表
     */
    private void getNewsChannel() {
        MyOkHttp.getInstance().getUrl(HttpUrl.CHANNEL_NEWS, new MyOkHttp.Header("apikey", HttpUrl.BAIDU_API_KEY), null, new MyOkHttp.RequestCallBack() {
            @Override
            public void onFailure(Exception httpException, String describe) {

            }

            @Override
            public void onSuccess(String result) {
//                ALog.i("新闻分类:" + result);
                MyLog.json(result);
                parseNewsChannel(result);
            }
        });

    }

    /**
     * 将请求到的新闻面板数据转换成对象,并设置到view
     *
     * @param result
     */
    private void parseNewsChannel(String result) {
        NewsChannelEntity newsChannelEntity = JsonUtils.fromJson(result, NewsChannelEntity.class);
        if (newsChannelEntity == null || newsChannelEntity.getShowapi_res_body() == null
                || newsChannelEntity.getShowapi_res_body().getChannelList() == null) {

        } else {
            channelLists.clear();
            channelLists.addAll(newsChannelEntity.getShowapi_res_body().getChannelList());
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setNewsChanelView();
            }
        });
    }

    /**
     * 设置新闻面板数据
     */
    private void setNewsChanelView() {
        rcv_home_news_channel = (RecyclerView) rootView.findViewById(R.id.rcv_home_news_channel);
        rcv_home_news_channel.setLayoutManager(new GridLayoutManager(mActivity, 3));
        rcv_home_news_channel.setAdapter(new NewsChannelAdapter(mActivity, channelLists));
    }

    /**
     * 获取天气信息
     */
    public void getLoacation() {
        //根据地理位置获取天气信息.需要添加百度定位
        BaiDuLbsUtil.getInstance().start(new BaiDuLbsUtil.LocationCallBack() {
            @Override
            public void localtionInfo(String countryName, String provinceName, String cityName, String district) {
                MyLog.i(countryName + provinceName + cityName + district);
                if (provinceName != null && provinceName.length() > 0) {
                    provinceName = provinceName.substring(0, provinceName.length() - 1);
                }
                if (district != null && district.length() > 0) {
                    district = district.substring(0, district.length() - 1);
                }
                getWeather(provinceName, district);
            }
        });
    }

    private void getWeather(String provinceName, String district) {
        tv_home_weather_info.setText(district);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("key", HttpUrl.MOB_API_KEY);
        hashMap.put("city", district);
        hashMap.put("province", provinceName);
        MyOkHttp.getInstance().getUrl(HttpUrl.WEATHER_QUERY, hashMap, new MyOkHttp.RequestCallBack() {
            @Override
            public void onFailure(Exception httpException, String describe) {
            }

            @Override
            public void onSuccess(String result) {
                parseWeather(result);
            }
        });

    }

    private void parseWeather(String result) {
        WeatherQueryEntity weatherQueryEntity = JsonUtils.fromJson(result, WeatherQueryEntity.class);
        if (weatherQueryEntity == null || weatherQueryEntity.getResult() == null) {

        } else {
            weatherQueryEntityResult = weatherQueryEntity.getResult();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setWeatherView();
                }
            });
        }
    }

    private void setWeatherView() {
        if (weatherQueryEntityResult == null || weatherQueryEntityResult.isEmpty()) {

        } else {
            WeatherQueryEntity.Result result = weatherQueryEntityResult.get(0);
            String distrct = result.getDistrct();
            String weather = result.getWeather();
            String temperature = result.getTemperature();
            tv_home_weather_info.setText(distrct + "  " + weather + " " + temperature);
        }
    }

    public class NewsChannelAdapter extends BaseRecyclerViewAdapter<NewsChannelHolder> {
        Activity mActivity;
        List<NewsChannelEntity.ShowapiResBody.ChannelList> mChannelLists;

        public NewsChannelAdapter(Activity activity, List<NewsChannelEntity.ShowapiResBody.ChannelList> channelLists) {
            mActivity = activity;
            mChannelLists = channelLists;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            FrameLayout frameLayout = new FrameLayout(mActivity);
            NewsChannelHolder newsChannelHolder = new NewsChannelHolder(frameLayout);
            newsChannelHolder.tv_news_channel_name = new TextView(mActivity);
            frameLayout.addView(newsChannelHolder.tv_news_channel_name);
            return newsChannelHolder;
        }

        @Override
        public int getItemCount() {
            if (mChannelLists == null || mChannelLists.isEmpty()) {
                return 0;
            }
            return mChannelLists.size();
        }

        @Override
        public void onBindViewHolder(NewsChannelHolder holder, final int position, boolean isBaseRecyclerViewAdapter) {
            holder.tv_news_channel_name.setText(mChannelLists.get(position).getName());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, NewsListActivity.class);
                    intent.putExtra(Extras.CHANNEL_ID, mChannelLists.get(position).getChannelId());
                    intent.putExtra(Extras.CHANNEL_NAME, mChannelLists.get(position).getName());
                    mActivity.startActivity(intent);
                }
            });
        }


    }

    class NewsChannelHolder extends RecyclerView.ViewHolder {
        TextView tv_news_channel_name;

        public NewsChannelHolder(View itemView) {
            super(itemView);
        }
    }
}
